package com.uwo.commons.configuration.aop.validate.validate;

import com.uwo.commons.configuration.aop.validate.ErrorCode;
import com.uwo.commons.configuration.aop.validate.ValidateField;
import com.uwo.commons.configuration.aop.validate.ValidateProperties;
import com.uwo.commons.configuration.aop.validate.annotation.Length;
import com.uwo.commons.configuration.aop.validate.excepteion.ApiValidateExceptrion;
import com.uwo.commons.kits.StringKits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

/**
 * 设置字符串长度
 * @author hao.yan
 */
@Component(value = "Validate_Length")
public class LengthValidate extends NotNullValidate{

    @Autowired
    private ValidateProperties validateProperties;

    @Override
    public void validate(Annotation annotation, ValidateField validateField) throws ApiValidateExceptrion {
        super.validate(annotation, validateField);
        if (validateField.getValue() instanceof String) {
            int strLen = String.valueOf(validateField.getValue()).length();
            Length len = (Length)annotation;
            if (strLen < len.min()){
                // 属性配置
                String message = value(validateProperties.getMessages(), len.message(),
                        ErrorCode.MIN_LENGTH.getMessage(validateField.getName(), strLen));
                exception(len.code(), message, ErrorCode.MIN_LENGTH);
            }
            if (strLen > len.max()){
                // 属性配置
                String message = value(validateProperties.getMessages(), len.message(),
                        ErrorCode.MAX_LENGTH.getMessage(validateField.getName(), strLen));
                exception(len.code(), message, ErrorCode.MAX_LENGTH);
            }
        }
    }

}
